package com.highcom.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurrityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用 BCrypt 加密
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()                   //  定义当需要用户登录时候，转到的登录页面。
                .loginPage("/pages/login.html")           // 设置登录页面
                .loginProcessingUrl("/login").
                usernameParameter("username").
                passwordParameter("password") .successHandler(successHandler())// 自定义的登录接口
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/pages/login.html").invalidateHttpSession(true).deleteCookies("JESSIONID").and()
                .authorizeRequests()       // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/pages/login.html").permitAll().antMatchers("/pages/mobile/*").permitAll()
                .and().authorizeRequests() .antMatchers("/setmeal/getSetmeal","/setmeal/findById","/order/submit","/order/findById","/validateCode/send4Order","/validateCode/send4Login","/member/login").permitAll().anyRequest().authenticated()
                .anyRequest()               // 任何请求,登录后可以访问
                .authenticated()
                .and().headers().frameOptions().sameOrigin().and()
                .csrf().disable();          // 关闭csrf防护
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置静态资源不要拦截
        web.ignoring().antMatchers("/css/**","/img/**","/js/**","/plugins/**");


    }

    SavedRequestAwareAuthenticationSuccessHandler successHandler(){
        SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
        handler.setDefaultTargetUrl("/pages/main.html");
        handler.setTargetUrlParameter("target");
        return handler;
    }

}
